package org.wattdepot.cli.command;

import java.util.List;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.cli.processor.CommandLineInterface;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.resource.sensordata.jaxb.SensorData;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * SensorDataTime Class.
 * 
 * @author Remy Baumgarten
 * @author Kevin Chiogioji
 * 
 */
public class SensorDataTime extends CommandLineInterface implements WattDepotCliCommand {

  /**
   * Command 2.5 - Prints information about a single sensor data instance.
   * 
   * @param args -
   * @return SensorData -
   */
  public String doCommand(List<String> args) {
    String source = args.get(0);
    String timestamp = args.get(1);
    XMLGregorianCalendar time = null;
    SensorData sensorData = null;
    StringBuffer buff = new StringBuffer(255);
    String data = null;
    try {
      time = Tstamp.makeTimestamp(timestamp);
      sensorData = client.getSensorData(source, time);

      buff.append("Tool: ").append(sensorData.getTool()).append(cr);
      buff.append("Source: ").append(
          sensorData.getSource().toString().substring(
              sensorData.getSource().toString().lastIndexOf('/') + 1,
              sensorData.getSource().toString().length()));
      buff.append(cr);
      buff.append("Properties: ");
      if (sensorData.isSetProperties()) {
        data = sensorData.getProperties().getProperty().toString();
        buff.append('(').append(data.substring(data.indexOf('=') + 1, data.indexOf(','))).append(
            ": ").append(data.substring(data.lastIndexOf('=') + 1, data.length() - 2)).append(')');
      }
      else {
        buff.append("none");
      }
    }
    catch (MiscClientException mce) {
      return errorClient;
    }
    catch (BadXmlException bxe) {
      return errorXML;
    }
    catch (ResourceNotFoundException rnfe) {
      return error404;
    }
    catch (NotAuthorizedException nae) {
      return error401;
    }
    catch (Exception e) {
      return errorTimeStamp;
    }
    return buff.toString();
  }
}
